/**
 * 研发流程状态机 - 状态转换规则定义
 * 根据研发流程状态机.md文档实现
 */

const { STATE_CODES } = require('./research_state');

/**
 * 状态转换事件定义
 */
const STATE_EVENTS = {
  // 项目审核事件
  APPROVE_DIRECTOR: {
    code: 'approve_director',
    name: '董事长审核通过',
    description: '项目立项初审通过，转至研发经理审核'
  },
  REJECT_DIRECTOR: {
    code: 'reject_director',
    name: '董事长审核不通过',
    description: '项目立项不通过，归档'
  },
  APPROVE_MANAGER: {
    code: 'approve_manager',
    name: '研发经理审核通过',
    description: '项目可行性审核通过，进入分配阶段'
  },
  REJECT_MANAGER: {
    code: 'reject_manager',
    name: '研发经理审核不通过',
    description: '项目审核不通过，归档'
  },
  ASSIGN_PROJECT: {
    code: 'assign_project',
    name: '分配项目',
    description: '分配项目负责人和资源'
  },
  
  // 休眠事件
  APPROVE_DORMANT: {
    code: 'approve_dormant',
    name: '同意休眠',
    description: '审核通过项目休眠申请'
  },
  REJECT_DORMANT: {
    code: 'reject_dormant',
    name: '拒绝休眠',
    description: '审核不通过项目休眠申请'
  },
  WAKEUP_REQUEST: {
    code: 'wakeup_request',
    name: '唤醒申请',
    description: '申请重新启动休眠项目'
  },
  
  // 硬件确认事件
  HARDWARE_CHANGE: {
    code: 'hardware_change',
    name: '无现成硬件/硬件变更',
    description: '需要新设计硬件'
  },
  HARDWARE_EXISTING: {
    code: 'hardware_existing',
    name: '已有硬件/软件变更',
    description: '使用现有硬件，只需要软件变更'
  },
  
  // 硬件设计阶段事件
  DESIGN_SUBMIT: {
    code: 'design_submit',
    name: '提交审核',
    description: '硬件设计完成，提交审核'
  },
  DESIGN_APPROVE: {
    code: 'design_approve',
    name: '审核通过',
    description: '硬件设计审核通过'
  },
  DESIGN_REJECT: {
    code: 'design_reject',
    name: '审核不通过',
    description: '硬件设计审核不通过，返回修改'
  },
  PURCHASE_COMPLETE: {
    code: 'purchase_complete',
    name: '到料完成',
    description: '物料采购完成'
  },
  PURCHASE_ISSUE: {
    code: 'purchase_issue',
    name: '物料异常',
    description: '物料采购发现异常'
  },
  SAMPLE_COMPLETE: {
    code: 'sample_complete',
    name: '样品完成',
    description: '样品制作完成'
  },
  REQUEST_DEBUG: {
    code: 'request_debug',
    name: '申请样品调试',
    description: '申请领用样品进行调试'
  },
  
  // 调试阶段事件
  DEBUG_COMPLETE: {
    code: 'debug_complete',
    name: '调试完成',
    description: '软硬件调试完成'
  },
  NO_TEST_REQUEST: {
    code: 'no_test_request',
    name: '免测试申请',
    description: '申请免除测试环节'
  },
  HARDWARE_CONFIRM_AGAIN: {
    code: 'hardware_confirm_again',
    name: '硬件确认',
    description: '需要重新确认硬件'
  },
  DATA_SYNC_REQUEST: {
    code: 'data_sync_request',
    name: '资料同步',
    description: '同步项目资料给其他人员'
  },
  
  // 资料同步事件
  SYNC_COMPLETE: {
    code: 'sync_complete',
    name: '同步完成',
    description: '资料同步完成'
  },
  
  // 测试阶段事件
  TEST_PASS: {
    code: 'test_pass',
    name: '测试通过',
    description: '测试验证通过'
  },
  TEST_FAIL: {
    code: 'test_fail',
    name: '测试不通过',
    description: '测试验证不通过，返回调试'
  },
  NO_TEST_APPROVE: {
    code: 'no_test_approve',
    name: '免测试审核通过',
    description: '免测试申请审核通过'
  },
  NO_TEST_REJECT: {
    code: 'no_test_reject',
    name: '免测试审核不通过',
    description: '免测试申请审核不通过'
  },
  
  // 客户确认阶段事件
  SAMPLE_SHIPPING: {
    code: 'sample_shipping',
    name: '寄样',
    description: '寄送样品给客户'
  },
  CUSTOMER_RECEIVED: {
    code: 'customer_received',
    name: '到样',
    description: '客户收到样品'
  },
  CUSTOMER_SIGN: {
    code: 'customer_sign',
    name: '签样确认',
    description: '客户签收样品确认'
  },
  NO_SIGN_REQUEST: {
    code: 'no_sign_request',
    name: '申请无签样',
    description: '申请无客户签样确认'
  },
  NO_SIGN_MANAGER_APPROVE: {
    code: 'no_sign_manager_approve',
    name: '研发经理审核通过',
    description: '无签样申请研发经理审核通过'
  },
  NO_SIGN_DIRECTOR_APPROVE: {
    code: 'no_sign_director_approve',
    name: '董事长审核通过',
    description: '无签样申请董事长审核通过'
  },
  NO_SIGN_REJECT: {
    code: 'no_sign_reject',
    name: '审核不通过',
    description: '无签样申请审核不通过'
  },
  SAMPLE_STORAGE_CONFIRM: {
    code: 'sample_storage_confirm',
    name: '样品入库确认',
    description: '样品入库管理确认'
  },
  ARCHIVE_COMPLETE: {
    code: 'archive_complete',
    name: '归档完成',
    description: '客户确认资料归档完成'
  },
  FUNCTION_ISSUE: {
    code: 'function_issue',
    name: '发现功能问题',
    description: '客户确认过程中发现功能问题'
  },
  
  // 订单准备阶段事件
  ORDER_REQUEST: {
    code: 'order_request',
    name: '订单申请',
    description: '提交订单申请'
  },
  ORDER_APPROVE: {
    code: 'order_approve',
    name: '订单审核通过',
    description: '订单申请审核通过'
  },
  ORDER_REJECT: {
    code: 'order_reject',
    name: '订单审核不通过',
    description: '订单申请审核不通过'
  },
  DOC_SEND_COMPLETE: {
    code: 'doc_send_complete',
    name: '发送完成',
    description: '生产资料发送完成'
  },
  DOC_INCOMPLETE: {
    code: 'doc_incomplete',
    name: '资料不完整',
    description: '生产资料不完整，需要补充'
  },
  DOC_SUPPLEMENT_COMPLETE: {
    code: 'doc_supplement_complete',
    name: '资料补充完成',
    description: '生产资料补充完成'
  },
  MEETING_COMPLETE: {
    code: 'meeting_complete',
    name: '会议完成',
    description: '产前会议完成'
  },
  PREPARATION_COMPLETE: {
    code: 'preparation_complete',
    name: '生产准备完成',
    description: '生产准备工作完成'
  },
  
  // 生产阶段事件
  PRODUCTION_ISSUE: {
    code: 'production_issue',
    name: '生产问题反馈',
    description: '生产过程中发现问题'
  },
  PE_ISSUE_SOLVED: {
    code: 'pe_issue_solved',
    name: '问题解决',
    description: 'PE解决生产问题'
  },
  RD_ISSUE_FOUND: {
    code: 'rd_issue_found',
    name: '发现设计问题',
    description: '生产中发现设计问题'
  },
  RD_ISSUE_SOLVED: {
    code: 'rd_issue_solved',
    name: '问题解决',
    description: '研发解决设计问题'
  },
  PRODUCTION_COMPLETE: {
    code: 'production_complete',
    name: '生产完成',
    description: '生产工作完成'
  },
  
  // 通用事件
  SLEEP_REQUEST: {
    code: 'sleep_request',
    name: '休眠申请',
    description: '申请项目休眠'
  },
  REDESIGN_REQUEST: {
    code: 'redesign_request',
    name: '重设计申请',
    description: '申请项目重新设计'
  },
  CANCEL_ORDER: {
    code: 'cancel_order',
    name: '取消订单',
    description: '取消订单申请'
  },
  CANCEL_FUNCTION_ISSUE: {
    code: 'cancel_function_issue',
    name: '撤销功能问题',
    description: '撤销之前提出的功能问题'
  },
  
  // 项目结束事件
  PROJECT_END: {
    code: 'project_end',
    name: '项目终结',
    description: '项目完成终结'
  },
  RETURN_TO_DEBUG: {
    code: 'return_to_debug',
    name: '项目返回调试',
    description: '项目返回调试阶段'
  }
};

/**
 * 状态转换规则定义
 */
const TRANSITIONS = [
  // === 项目审核阶段转换 ===
  {
    from: { state: 'project_review', subState: 'director_review' },
    to: { state: 'project_review', subState: 'manager_review' },
    event: 'APPROVE',
    roles: ['director'],
    condition: (data) => true
  },
  {
    from: { state: 'project_review', subState: 'director_review' },
    to: { state: 'dormant', subState: 'archived' },
    event: 'REJECT',
    roles: ['director'],
    condition: (data) => !!data.rejectReason
  },
  {
    from: { state: 'project_review', subState: 'manager_review' },
    to: { state: 'project_review', subState: 'assignment' },
    event: 'APPROVE',
    roles: ['research_manager'],
    condition: (data) => true
  },
  {
    from: { state: 'project_review', subState: 'assignment' },
    to: { state: 'active', subState: 'hardware_confirm' },
    event: 'SUBMIT',
    roles: ['research_manager'],
    condition: (data) => !!data.hardwareEngineer && !!data.softwareEngineer
  },
  
  // === 项目审核与活动状态间的转换 ===
  {
    from: { state: 'project_review', subState: 'assignment' },
    to: { state: 'active', subState: 'hardware_confirm' },
    event: 'APPROVE_DESIGN_CHANGE',
    roles: ['research_manager'],
    condition: (data) => true
  },
  
  // === 休眠状态转换 ===
  {
    from: { state: 'active', subState: '*' },
    to: { state: 'dormant', subState: 'review' },
    event: 'HIBERNATE',
    roles: ['business'],
    condition: (data) => !!data.hibernateReason
  },
  {
    from: { state: 'dormant', subState: 'review' },
    to: { state: 'dormant', subState: 'archived' },
    event: 'APPROVE',
    roles: ['research_manager'],
    condition: (data) => true
  },
  {
    from: { state: 'dormant', subState: 'review' },
    to: { state: 'active', subState: 'PREV_ACTIVE' },
    event: 'REJECT',
    roles: ['research_manager'],
    condition: (data) => true
  },
  
  // === 休眠到项目审核的转换 ===
  {
    from: { state: 'dormant', subState: '*' },
    to: { state: 'project_review', subState: 'manager_review' },
    event: 'AWAKEN',
    roles: ['business'],
    condition: (data) => !!data.awakenReason
  },
  
  // === 活动状态的内部转换 ===
  {
    from: { state: 'active', subState: 'hardware_confirm' },
    to: { state: 'active', subState: 'hardware' },
    event: 'NO_HARDWARE',
    roles: ['hw_engineer'],
    condition: (data) => true
  },
  {
    from: { state: 'active', subState: 'hardware_confirm' },
    to: { state: 'active', subState: 'debug' },
    event: 'HAS_HARDWARE',
    roles: ['hw_engineer'],
    condition: (data) => true
  },
  
  // === 硬件阶段转换 ===
  {
    from: { state: 'active', subState: 'hardware' },
    to: { state: 'active', subState: 'debug' },
    event: 'REQUEST_DEBUG',
    roles: ['sw_engineer'],
    condition: (data) => true
  },
  
  // === 调试阶段转换 ===
  {
    from: { state: 'active', subState: 'debug' },
    to: { state: 'active', subState: 'test' },
    event: 'DEBUG_COMPLETE',
    roles: ['sw_engineer'],
    condition: (data) => true
  },
  {
    from: { state: 'active', subState: 'debug' },
    to: { state: 'active', subState: 'data_sync' },
    event: 'SYNC_DATA',
    roles: ['sw_engineer'],
    condition: (data) => true
  },
  {
    from: { state: 'active', subState: 'debug' },
    to: { state: 'active', subState: 'hardware_confirm' },
    event: 'RECONFIRM_HARDWARE',
    roles: ['sw_engineer'],
    condition: (data) => true
  },
  
  // === 资料同步阶段转换 ===
  {
    from: { state: 'active', subState: 'data_sync' },
    to: { state: 'active', subState: 'test' },
    event: 'SYNC_COMPLETE',
    roles: ['sw_engineer_delegate'],
    condition: (data) => true
  },
  
  // === 测试阶段转换 ===
  {
    from: { state: 'active', subState: 'test' },
    to: { state: 'active', subState: 'customer_validation' },
    event: 'TEST_PASS',
    roles: ['test_team'],
    condition: (data) => true
  },
  {
    from: { state: 'active', subState: 'test' },
    to: { state: 'active', subState: 'debug' },
    event: 'TEST_FAIL',
    roles: ['test_team'],
    condition: (data) => !!data.testReport
  },
  
  // === 客户验证阶段转换 ===
  {
    from: { state: 'active', subState: 'customer_validation' },
    to: { state: 'active', subState: 'order_prepare' },
    event: 'REQUEST_ORDER',
    roles: ['business'],
    condition: (data) => true
  },
  {
    from: { state: 'active', subState: 'customer_validation' },
    to: { state: 'active', subState: 'debug' },
    event: 'ISSUE_FOUND',
    roles: ['business'],
    condition: (data) => !!data.issueDescription
  },
  
  // === 订单准备阶段转换 ===
  {
    from: { state: 'active', subState: 'order_prepare' },
    to: { state: 'active', subState: 'customer_validation' },
    event: 'CANCEL_ORDER',
    roles: ['business'],
    condition: (data) => !!data.cancelReason
  },
  {
    from: { state: 'active', subState: 'order_prepare' },
    to: { state: 'active', subState: 'production' },
    event: 'PREPARE_COMPLETE',
    roles: ['production_admin'],
    condition: (data) => data.allIssuesResolved === true
  },
  
  // === 生产阶段转换 ===
  {
    from: { state: 'active', subState: 'production' },
    to: { state: 'active', subState: 'customer_validation' },
    event: 'CANCEL_PRODUCTION',
    roles: ['business'],
    condition: (data) => !!data.cancelReason
  },
  {
    from: { state: 'active', subState: 'production' },
    to: { state: 'active', subState: 'pending_feedback' },
    event: 'PRODUCTION_COMPLETE',
    roles: ['production_manager'],
    condition: (data) => true
  },
  
  // === 待反馈阶段转换 ===
  {
    from: { state: 'active', subState: 'pending_feedback' },
    to: { state: 'active', subState: 'order_prepare' },
    event: 'REQUEST_ORDER',
    roles: ['business'],
    condition: (data) => true
  },
  {
    from: { state: 'active', subState: 'pending_feedback' },
    to: { state: 'active', subState: 'debug' },
    event: 'ISSUE_FOUND',
    roles: ['business'],
    condition: (data) => !!data.issueDescription
  },
  
  // === 重设计申请 ===
  {
    from: { state: 'active', subState: '*' },
    to: { state: 'project_review', subState: 'manager_review' },
    event: 'REQUEST_REDESIGN',
    roles: ['business'],
    condition: (data) => !!data.redesignReason
  }
];

/**
 * 获取状态转换规则
 * @param {Object} fromState 源状态
 * @param {String} eventCode 事件编码
 * @returns {Object} 转换规则对象
 */
function getTransition(fromState, eventCode) {
  if (!fromState || !eventCode) return null;
  
  return TRANSITIONS.find(t => 
    t.event === eventCode && 
    t.from.state.main === fromState.main &&
    (!t.from.state.active || t.from.state.active === fromState.active) &&
    (!t.from.state.sub || t.from.state.sub === fromState.sub)
  );
}

/**
 * 获取当前状态可用的事件列表
 * @param {Object} currentState 当前状态
 * @param {String} currentRole 当前角色
 * @returns {Array} 可用事件列表
 */
function getAvailableEvents(currentState, currentRole) {
  if (!currentState) return [];
  
  const events = [];
  
  // 查找当前状态可用的所有转换规则
  TRANSITIONS.forEach(transition => {
    const t = transition.from.state;
    const s = currentState;
    
    // 匹配状态
    if (t.main === s.main && 
        (!t.active || t.active === s.active) && 
        (!t.sub || t.sub === s.sub)) {
      
      // 检查角色权限
      if (transition.roles.includes(currentRole) || transition.roles.includes('all') || currentRole === 'admin') {
        // 获取事件定义
        const eventDef = Object.values(STATE_EVENTS).find(e => e.code === transition.event);
        
        if (eventDef) {
          events.push({
            id: eventDef.code,
            name: eventDef.name,
            description: eventDef.description,
            toState: transition.to.state,
            requiredDocs: transition.requiredDocs || []
          });
        }
      }
    }
  });
  
  // 添加通用事件
  if (currentState.main === STATE_CODES['ACTIVE'].main) {
    // 在活动状态下添加休眠申请事件
    if (['business_staff', 'admin'].includes(currentRole)) {
      events.push({
        id: STATE_EVENTS.SLEEP_REQUEST.code,
        name: STATE_EVENTS.SLEEP_REQUEST.name,
        description: STATE_EVENTS.SLEEP_REQUEST.description,
        toState: STATE_CODES['DORMANT.REVIEW'],
        requiredDocs: [
          { type: 'sleep_reason', name: '休眠原因' }
        ]
      });
    }
    
    // 在活动状态下添加重设计申请事件
    if (['business_staff', 'admin'].includes(currentRole)) {
      events.push({
        id: STATE_EVENTS.REDESIGN_REQUEST.code,
        name: STATE_EVENTS.REDESIGN_REQUEST.name,
        description: STATE_EVENTS.REDESIGN_REQUEST.description,
        toState: STATE_CODES['PROJECT_REVIEW.MANAGER_REVIEW'],
        requiredDocs: [
          { type: 'redesign_reason', name: '重设计原因' }
        ]
      });
    }
  }
  
  return events;
}

/**
 * 导出状态转换相关功能
 */
module.exports = {
  STATE_EVENTS,
  TRANSITIONS,
  getTransition,
  getAvailableEvents
}; 